package com.pipe.protocol.events.other;

import com.pipe.util.MyBytebufUtil;
import com.pipe.util.MysqlProtocolUtil;
import io.netty.buffer.ByteBuf;

import java.util.Arrays;

/**
 * @author Kiven
 * @see <a href="https://dev.mysql.com/doc/internals/en/format-description-event.html">mysql internal doc</a>
 */
public class FormatDescriptionEvent {
    private int binlogVersion;
    private String mysqlServerVersion;
    private long timestamp;
    private byte eventHeaderLength;
    private byte[] eventTypeHeaderLengths;

    public FormatDescriptionEvent(int binlogVersion, String mysqlServerVersion, long timestamp, byte eventHeaderLength, byte[] eventTypeHeaderLengths) {
        this.binlogVersion = binlogVersion;
        this.mysqlServerVersion = mysqlServerVersion;
        this.timestamp = timestamp;
        this.eventHeaderLength = eventHeaderLength;
        this.eventTypeHeaderLengths = eventTypeHeaderLengths;
    }

    public static FormatDescriptionEvent build(ByteBuf byteBuf){
        int binlogVersion = byteBuf.readUnsignedShortLE();
        String mysqlServerVersion = MyBytebufUtil.readStringFromBytebuf(byteBuf, 50);
        long timestamp = (long)byteBuf.readUnsignedIntLE() * 1000;;
        byte eventHeaderLength = byteBuf.readByte();
        byte[] eventTypeHeaderLengths = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(eventTypeHeaderLengths);

        return new FormatDescriptionEvent(binlogVersion, mysqlServerVersion, timestamp, eventHeaderLength, eventTypeHeaderLengths);
    }

    @Override
    public String toString() {
        return "FormatDescriptionEvent{" +
                "binlogVersion=" + binlogVersion +
                ", mysqlServerVersion='" + mysqlServerVersion + '\'' +
                ", timestamp=" + timestamp +
                ", eventHeaderLength=" + eventHeaderLength +
                ", eventTypeHeaderLengths=" + Arrays.toString(eventTypeHeaderLengths) +
                '}';
    }
}